<?php
/**
 * Created by PhpStorm.
 * User: silov
 * Date: 15/6/24
 * Time: 15:13
 */
namespace Home\Model;
use Think\Cache\Driver\Redis;
use Think\Model;
class AdminUserModel extends Model {
    protected $tableName = "admin_user";

    /**
     * @var 密码加密key
     */
    private $passKey;

    /**
     * @var string Api token redis key Pre_Uhash
     */
    private $tokenRedis = "AdminUserToken_";

    /**
     * 初始化密码加密算法key
     */
    protected function _initialize()
    {
        $this->passKey = md5("lOgInKeY!@#$Ω≈çç√∫");
    }

    /**
     * @param  string $username 用户名
     * @param  string $mdpass 前端md5加密明文密码的值
     * @return string 最终存储的密码
     */
    private function getPassword($username, $mdpass)
    {
        $tmp = [
            'u' => $username,
            'p' => $mdpass
        ];

        ksort($tmp);

        return md5( base64_encode( http_build_query($tmp).$this->passKey ) );
    }

    /**
     * 账号密码登录
     * @param $username
     * @param $password
     * @return mixed
     */
    public function loginWithUsername($username, $password)
    {
        $finnalPassword = $this->getPassword($username, $password);

        $condition = [
            'username'  => $username,
            'password'  => $finnalPassword
        ];
        $row = $this->where($condition)->select();

        if ( !$row || $row[0]['status'] !=1 ) {
            return [
                'status'    => false,
                'code'      => 10002,
                'msg'       => '昵称或密码错误!'
            ];
        }
        $userInfo = $this->formatUser($row[0]);

        //生成新token
        //$token = md5( http_build_query($userInfo) . time() );
        //$userInfo['token'] = $token;

        //存储token到Redis
        //$redis = new Redis();
        //$redis->set($this->tokenRedis . $userInfo['hash'] , $token);

        session("uid", $userInfo['id']);
        //session("username", $userInfo['username']);
        //session("real_name", $userInfo['real_name']);

        return [
            'status'    => true,
            'userInfo'  => $userInfo
        ];
    }

    /**
     * 格式化用户信息
     * @param $user
     * @return mixed
     */
    public function formatUser($user)
    {
        unset($user['password']);
        $user['created'] = date("Y-m-d");
        return $user;
    }

    /**
     * 校验原始密码
     * @param $uid
     * @param $password
     * @return array
     */
    public function checkPassword($uid, $password) {
        $condition = ['id'    => $uid];
        $user = $this->where($condition)->find();

        if (!$user) {
            return [
                'status'    => false,
                'code'      => 10001,
                'msg'       => '用户不存在!'
            ];
        }

        $finnalPass = $this->getPassword($user['username'], $password);
        if ($finnalPass == $user['password']) {
            return [
                'status'    => true
            ];
        } else {
            return [
                'status'    => false,
                'code'      => 10002,
                'msg'       => '原始密码不匹配!'
            ];
        }
    }

    /**
     * 根据Uid获取用户信息
     * @param $uid
     * @return array
     */
    public function getAdminUserById($uid)
    {
        $condition = ['id'    => $uid];
        $user = $this->where($condition)->find();

        if ($user) {
            return $this->formatUser($user);
        } else {
            return [];
        }
    }

    public function newPassword($uid, $password) {
        $condition = ['id'    => $uid];
        $user = $this->where($condition)->find();

        if (!$user) {
            return [
                'status'    => false,
                'code'      => 10001,
                'msg'       => '用户不存在!'
            ];
        }

        $finnalPass = $this->getPassword($user['username'], $password);

        $res = $this->where($condition)->data(['password'=> $finnalPass])->save();
        if ($res) {
            return [
                'status'    => true,
                'code'      => 200,
                'msg'       => '更新密码成功!'
            ];
        } else {
            return [
                'status'    => false,
                'code'      => 10002,
                'msg'       => '更新失败,请重新操作!'
            ];
        }
    }
}